//
//  LoginViewController.m
//  QuickCure37
//
//  Created by 马文星 on 16/6/17.
//  Copyright © 2016年 Demos. All rights reserved.
//

#import "LoginViewController.h"
#import "NetWorkTool.h"
#import "MBProgressHUD+HM.h"
#import "RegisterViewController.h"

@interface LoginViewController ()

@property (nonatomic, strong) UIImageView * logoView;
@property (nonatomic, strong) UIImageView * logoLabel;
@property (nonatomic, strong) UITextField * accountTF;
@property (nonatomic, strong) UITextField * passwordTF;
@property (nonatomic, strong) UIButton    * loginButton;
//快速注册
@property (nonatomic, strong) UIButton *quickRegisterBtn;
//忘记密码
@property (nonatomic, strong) UIButton *forgetPasswordBtn;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.accountTF.text = [defaults valueForKey:@"username"];
    //self.passwordTF.text = [defaults valueForKey:@"password"];

    [self setupUI];
}


-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [self.view endEditing:YES];
}

- (void)setupUI{

    self.title = @"登录";
    self.accountTF.font = [UIFont fontWithName:@"CloudShuiZhuGBK" size:18];
    self.passwordTF.font = [UIFont fontWithName:@"CloudShuiZhuGBK" size:18];
    self.quickRegisterBtn.titleLabel.font = [UIFont fontWithName:@"CloudShuiZhuGBK" size:15];
    self.forgetPasswordBtn.titleLabel.font = [UIFont fontWithName:@"CloudShuiZhuGBK" size:15];
    self.loginButton.titleLabel.font = [UIFont fontWithName:@"CloudShuiZhuGBK" size:20];
    
    /*!
     *  添加
     */
    [self.view addSubview:self.logoView];
    [self.view addSubview:self.logoLabel];
    [self.view addSubview:self.accountTF];
    [self.view addSubview:self.passwordTF];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.quickRegisterBtn];
    [self.view addSubview:self.forgetPasswordBtn];
    
    /*!
     *  设置布局
     */
    
    CGFloat padding = (SCREEN_WIDTH==320) ? 10 : 70;
    
    [self.logoView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(64+padding);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(70, 90));
    }];
    
    [self.logoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.logoView.mas_bottom).offset(2);
        make.centerX.equalTo(self.logoView);
        make.size.mas_equalTo(CGSizeMake(70, 45));
    }];
    
    [self.accountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.logoLabel.mas_bottom).offset(20);
        make.height.mas_equalTo(35);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
    }];
    
    [self.passwordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.accountTF.mas_bottom).offset(20);
        make.height.mas_equalTo(35);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
    }];
    
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.passwordTF.mas_bottom).offset(30);
        make.height.mas_equalTo(45);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
    }];
    
    [self.quickRegisterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.loginButton.mas_bottom).offset(20);
        make.left.mas_equalTo(self.loginButton);
        make.width.mas_equalTo(100);
    }];
    
    [self.forgetPasswordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.loginButton.mas_bottom).offset(20);
        make.right.mas_equalTo(self.loginButton);
        make.width.mas_equalTo(100);
    }];
}

#pragma mark - 点击登录
- (void)clickLoginBtn{
    
    NSString *url = @"http://127.0.0.1/login.php";
    
    NSString *account = self.accountTF.text;
    NSString *password = self.passwordTF.text;
    
    NSDictionary *dict = @{@"username":account,@"password":password};
    
    [[AFHTTPSessionManager manager] POST:url parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"userId"] intValue] == 1) {
            NSLog(@"OK");
            
            if (self.loginSuccessBlock) {
                self.loginSuccessBlock(YES);
            }
            //MBProgressHUD框架
            //显示菊花
            [MBProgressHUD showLoading];
            //延迟跳转
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //先移除菊花
                [MBProgressHUD removeAllHudForWindow];
                [MBProgressHUD showSuccessMessage:@"登录成功"];
                
                BaseNaviController *nvc = (BaseNaviController *)self.sidePanelController.centerPanel;
                [nvc popViewControllerAnimated:YES];
            });
            
            //存储登录成功状态
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//            [defaults setObject:@YES forKey:@"loginSuc"];
            [defaults setBool:YES forKey:@"loginSuc"];
            [defaults setObject:@"zhangsan" forKey:@"username"];
            [defaults setObject:@"zhang" forKey:@"password"];

            [defaults setBool:YES forKey:@"autoLogin"];
            //设置同步
            [defaults synchronize];
            
            //发通知改登录状态的值
            [[NSNotificationCenter defaultCenter]postNotificationName:@"islogin" object:@(1)];
            
        }else{
            //方法子
            [self showAlertWithTitle:@"输入的用户名或密码错误" message:@"请重新输入"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
    }];

}
//方法子
- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark - 快速注册
- (void)registerQuickly{
    
    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
    
    [self.navigationController pushViewController:registerVC animated:YES];
}


#pragma mark  - Actions
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.view endEditing:YES];
}

#pragma mark  - Lazy
- (UIImageView *)logoView{

    if (_logoView == nil) {
        _logoView = [[UIImageView alloc] init];
        _logoView.image = [UIImage imageNamed:@"product_img_logo_nor.png"];
    }
    return _logoView;
}

- (UIImageView *)logoLabel{
    
    if (_logoLabel == nil) {
        _logoLabel = [[UIImageView alloc] init];
        _logoLabel.image = [UIImage imageNamed:@"product_text_logo_nor.png"];
    }
    return _logoLabel;
}


- (UITextField *)accountTF{
    if (_accountTF == nil) {
        _accountTF = [[UITextField alloc] init];
        _accountTF.placeholder = @"请输入账户";
        _accountTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        _accountTF.borderStyle = UITextBorderStyleRoundedRect;
        _accountTF.autocapitalizationType = UITextAutocapitalizationTypeNone;

    }
    return _accountTF;

}

- (UITextField *)passwordTF{
    if (_passwordTF == nil) {
        _passwordTF = [[UITextField alloc] init];
        _passwordTF.placeholder = @"请输入密码";
        _passwordTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        _passwordTF.borderStyle = UITextBorderStyleRoundedRect;
        _passwordTF.autocapitalizationType = UITextAutocapitalizationTypeNone;
        [_passwordTF setSecureTextEntry:YES];
    }
    return _passwordTF;
}

-(UIButton *)loginButton{

    if (_loginButton == nil) {
        _loginButton = [[UIButton alloc] init];
        [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
        [_loginButton setTitle:@"" forState:UIControlStateHighlighted];
        _loginButton.backgroundColor = kThemeColor;
        _loginButton.titleLabel.font = FONT(20);
        
        [_loginButton addTarget:self action:@selector(clickLoginBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

//快速注册
- (UIButton *)quickRegisterBtn{
    if (_quickRegisterBtn == nil) {
        _quickRegisterBtn = [[UIButton alloc] init];
        [_quickRegisterBtn setTitle:@"快速注册" forState:UIControlStateNormal];
        [_quickRegisterBtn setTitle:@"" forState:UIControlStateHighlighted];
        //_quickRegisterBtn.backgroundColor = kThemeColor;
        [_quickRegisterBtn setTitleColor:kThemeColor forState:UIControlStateNormal];
        _quickRegisterBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_quickRegisterBtn addTarget:self action:@selector(registerQuickly) forControlEvents:UIControlEventTouchUpInside];
    }
    return _quickRegisterBtn;
}

- (UIButton *)forgetPasswordBtn{
    if (_forgetPasswordBtn == nil) {
        _forgetPasswordBtn = [[UIButton alloc] init];
        [_forgetPasswordBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
        [_forgetPasswordBtn setTitle:@"" forState:UIControlStateHighlighted];
        //_forgetPasswordBtn.backgroundColor = kThemeColor;
        [_forgetPasswordBtn setTitleColor:kThemeColor forState:UIControlStateNormal];
        _forgetPasswordBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    }
    return _forgetPasswordBtn;
}

@end
